// pages/list/list.js
/* 
	wx.setNavigationBarTitle(Object object)  动态设置当前页面的标题

	美食店铺: https://locally.uieee.com/categories/1/shops
	限制分页
	https://locally.uieee.com/categories/1/shops?_page=1&_limit=10
*/
const fetch = require("../../utils/fetch.js")

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		// 当前加载的分类
		category: {},
		// 此分类下的的商品
		shops: [],
		page: 0,
		pageLimit: 15,
		counts: 0,
		hasMore: true,
		searchText: "",
		search: false
	},
	showSearch: function (e) {
		this.setData({
			searchText: e.detail.value,
			search: true
		})
	},
	// 取消搜索
	cancelSearch: function () {
		this.setData({
			searchText: "",
			search: false
		})
	},
	// 搜索
	searchClass: function (e) {
		this.setData({
			shops: [],
			page: 0,
			hasMore: true,
			searchText: e.detail.value
		})
		this.loadMore();
	},
	// 下拉加载更多
	loadMore: function (e) {
		// 判断商品数量
		if (!this.data.hasMore) return;
		let {page, pageLimit, searchText} = this.data;
		let params = {
			_page: ++page,
			_limit: pageLimit
		};
		if (searchText) params.q = searchText;

		return fetch(`categories/${ this.data.category.id }/shops`, params).then(res => {
			let shops = this.data.shops.concat(res.data)
			let counts = parseInt(res.header['X-Total-Count']);
			let hasMore = page * pageLimit <= counts
			this.setData({shops, page, counts, hasMore})
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		// console.log(options)
		fetch(`categories/${ options.cat }`).then(res => {
			this.setData({ category: res.data })
			wx.setNavigationBarTitle({ title: res.data.name })
			// 加载完分类后, 再去加载商铺信息
			this.loadMore();
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		if (this.data.category.name) {
			wx.setNavigationBarTitle({ title: this.data.category.name })
		}
	},
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
		// 清空数据
		this.setData({
			shops: [],
			page: 0,
			hasMore: true
		})
		// 加载数据
		this.loadMore().then(() => {
			wx.stopPullDownRefresh();
		});
	},
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		this.loadMore();
	}
})